// 示例：如何在其他控制器中使用Excel服务

import { Controller, Get, Res } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { FastifyReply } from 'fastify';
import { ExcelService } from '~/modules/tools/excel/excel.service';

@ApiTags('User - 用户')
@Controller('users')
export class UserController {
  constructor(
    private readonly excelService: ExcelService
  ) {}

  @Get('export')
  @ApiOperation({
    summary: '导出用户数据为Excel',
    description: '将用户数据导出为Excel文件并下载'
  })
  @ApiResponse({
    status: 200,
    description: '用户数据Excel文件下载成功'
  })
  async exportUsers(@Res() res: FastifyReply) {
    // 1. 获取用户数据
    const users = await this.getUserData();

    // 2. 定义Excel列
    const columns = [
      { header: '用户ID', key: 'id', width: 10 },
      { header: '用户名', key: 'username', width: 15 },
      { header: '邮箱', key: 'email', width: 25 },
      { header: '手机号', key: 'phone', width: 15 },
      { header: '注册时间', key: 'createdAt', width: 20 }
    ];

    // 3. 创建工作簿
    const workbook = await this.excelService.createWorkbook(
      '用户数据表',
      columns,
      users
    );

    // 4. 转换为Buffer
    const buffer = await this.excelService.workbookToBuffer(workbook);

    // 5. 设置响应头并发送文件
    const fileName = `users-${Date.now()}.xlsx`;
    res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.header('Content-Disposition', `attachment; filename="${fileName}"`);
    res.send(buffer);
  }

  private async getUserData() {
    // 模拟获取用户数据
    return [
      {
        id: 1,
        username: 'john_doe',
        email: 'john@example.com',
        phone: '13800138000',
        createdAt: new Date().toISOString()
      },
      {
        id: 2,
        username: 'jane_smith',
        email: 'jane@example.com',
        phone: '13800138001',
        createdAt: new Date().toISOString()
      }
    ];
  }
}
